﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace DentScan2.WebApp
{
    public partial class Default : Classes.BaseForm
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            CheckLogged();

            if (!IsPostBack)
            {
                int methodId = Request.QueryString["MethodId"] == null ? 1 : int.Parse(Request.QueryString["MethodId"]);
                ddlProductionYear.Items.Add(new ListItem("", ""));
                for (int i = 1930; i <= DateTime.Now.Year; i++)
                    ddlProductionYear.Items.Add(new ListItem(i.ToString(), i.ToString()));

                ddlDoors.Items.Add(new ListItem("", ""));
                ddlDoors.Items.Add(new ListItem("2/3", "2/3"));
                ddlDoors.Items.Add(new ListItem("4/5", "4/5"));

                if (Request.QueryString["notfound"] == "1")
                    this.Alert("Не е намерен търсения автомобил");

                if (Request.QueryString["NewDamage"] == "1")
                {
                    this.Damage = new Classes.Damage();
                    this.Damage.CalcData.LoadFromDatabase(this.AreaId.Value, methodId);
                    //Response.Redirect("FindCar.aspx", true);
                }

                if (Request.QueryString["Draft"] == "1")
                {
                    var draft = dl.Drafts.FirstOrDefault(d => d.UserId == this.UserId);
                    if (draft != null)
                    {
                        this.Damage = Classes.Damage.FromXml(draft.DraftXML);
                    }
                    else
                        this.Alert("Няма записана последна чернова");

                }


                if (Request.QueryString["DamageId"] != null)
                {
                    this.Damage = new Classes.Damage(dl.Damages.First(d => d.DamageId == Guid.Parse(Request.QueryString["DamageId"])));
                }

                if (Request.QueryString["OwnerId"] != null)
                {
                    this.Damage = new Classes.Damage();
                    this.Damage.CalcData.LoadFromDatabase(this.AreaId.Value, methodId);
                    Classes.Owner owner = new Classes.Owner(dl.Owners.First(o => o.OwnerId == Guid.Parse(Request.QueryString["OwnerId"])));
                    this.Damage.Car.Owner = owner;
                }

                if (Request.QueryString["CarId"] != null)
                {
                    this.Damage = new Classes.Damage();
                    this.Damage.CalcData.LoadFromDatabase(this.AreaId.Value, methodId);
                    Classes.Car car = new Classes.Car(dl.Cars.First(c => c.CarId == Guid.Parse(Request.QueryString["CarId"])));
                    this.Damage.Car = car;
                }

                if (this.Damage == null)
                {
                    this.Damage = new Classes.Damage();
                    this.Damage.CalcData.LoadFromDatabase(this.AreaId.Value, methodId);
                    if (methodId == -1)
                        this.Damage.JustHours = true;
                    this.Damage.TechName = this.FullName;
                    this.Damage.TechPhone = this.Phone;
                    SetData();
                }
                else
                    SetData();
                DB.Area area = dl.Areas.Where(a => a.AreaId == this.AreaId).FirstOrDefault();
                this.Damage.Currency = area.AWCurrency;
                this.Damage.OwnData = area.OwnData;
            }
        }




        protected void cvRegional_ServerValidate(object source, ServerValidateEventArgs args)
        {
            args.IsValid = ucRegional.CityId != null;

        }

        protected void cvVehicles_ServerValidate(object source, ServerValidateEventArgs args)
        {
            args.IsValid = ucVehicles.ModelId != null;
        }

        protected void cvInsurer_ServerValidate(object source, ServerValidateEventArgs args)
        {
            args.IsValid = ucInsDDL.SelectedId != null;
        }

        private void SetData()
        {
            tbActivity.Text = Damage.Car.Owner.Activity;
            tbAddress.Text = Damage.Car.Owner.Address;
            tbChassisNumber.Text = Damage.Car.ChassisNumber;
            tbContactPerson.Text = Damage.Car.Owner.ContactPerson;
            tbContactPhone.Text = Damage.Car.Owner.ContactPhone;
            tbDamageCode.Text = Damage.DamageCode;
            tbDamageDate.Text = Damage.DamageDate.HasValue ? Damage.DamageDate.Value.ToShortDateString() : "";
            tbDocumentNumber.Text = Damage.DocumentNumber;
            ddlDoors.SelectedValue = Damage.Car.Doors != null ? Damage.Car.Doors.ToString() : ""; ;
            tbEvaluatorName.Text = Damage.EvaluatorPerson;
            tbFaxes.Text = Damage.Car.Owner.Faxes;
            tbIdentifier.Text = Damage.Car.Owner.Identifier;
            tbKilometers.Text = Damage.Kilometers.HasValue ? Damage.Kilometers.ToString() : "";
            tbMOL.Text = Damage.Car.Owner.MOL;
            tbName.Text = Damage.Car.Owner.Name;
            tbPhones.Text = Damage.Car.Owner.Phones;
            tbPK.Text = Damage.Car.Owner.PK;
            ddlProductionYear.SelectedValue = Damage.Car.ProductionYear.HasValue ? Damage.Car.ProductionYear.Value.ToString() : "";
            tbRegNumber.Text = Damage.Car.RegNumber;
            UcCarTypeDDL.SelectedId = Damage.Car.CarTypeId;
            UcColorDDL.SelectedId = Damage.Car.ColorId;
            UcEvaluatorDDL.SelectedId = Damage.EvaluatorId;
            ucInsDDL.SelectedId = Damage.InsurerId;
            UcPaintDDL.SelectedId = Damage.Car.PaintId;
            ucRegional.CountryId = Damage.Car.Owner.CountryId;
            ucRegional.DistrictId = Damage.Car.Owner.DistrictId;
            ucRegional.CityId = Damage.Car.Owner.CityId;
            ucVehicles.MakeId = Damage.Car.MakeId;
            ucVehicles.ModelId = Damage.Car.ModelId;
            tbEmails.Text = Damage.Car.Owner.Emails;
            lDamageIdentifier.Text = Damage.DamageIdentifier.HasValue ? Damage.DamageIdentifier.Value.ToString() : "";
            lMethodName.Text = this.Damage.CalcData.MethodName;
        }

        private void GetData()
        {
            Damage.Car.Owner.Activity = tbActivity.Text.ToUpper();
            Damage.Car.Owner.Address = tbAddress.Text.ToUpper();
            Damage.Car.ChassisNumber = tbChassisNumber.Text.ToUpper();
            Damage.Car.Owner.ContactPerson = tbContactPerson.Text.ToUpper();
            Damage.Car.Owner.ContactPhone = tbContactPhone.Text.ToUpper();
            Damage.DamageCode = tbDamageCode.Text.ToUpper();
            Damage.DamageDate = tbDamageDate.Text != "" ? DateTime.Parse(tbDamageDate.Text) as DateTime? : null;
            Damage.DocumentNumber = tbDocumentNumber.Text;
            Damage.Car.Doors = ddlDoors.SelectedValue != "" ? ddlDoors.SelectedValue : null;
            Damage.EvaluatorPerson = tbEvaluatorName.Text.ToUpper();
            Damage.Car.Owner.Faxes = tbFaxes.Text.ToUpper();
            Damage.Car.Owner.Identifier = tbIdentifier.Text.ToUpper();
            Damage.Kilometers = tbKilometers.Text != "" ? int.Parse(tbKilometers.Text) as int? : null;
            Damage.Car.Owner.MOL = tbMOL.Text.ToUpper();
            Damage.Car.Owner.Name = tbName.Text.ToUpper();
            Damage.Car.Owner.Phones = tbPhones.Text.ToUpper();
            Damage.Car.Owner.PK = tbPK.Text.ToUpper();
            Damage.Car.ProductionYear = ddlProductionYear.SelectedValue != "" ? int.Parse(ddlProductionYear.SelectedValue) as int? : null;
            Damage.Car.RegNumber = tbRegNumber.Text.ToUpper();
            Damage.Car.CarTypeId = UcCarTypeDDL.SelectedId.Value;
            Damage.Car.ColorId = UcColorDDL.SelectedId;
            if (Damage.Car.ColorId.HasValue)
                Damage.Car.ColorName = dl.Colors.Where(c => c.ColorId == Damage.Car.ColorId).First().ColorName.ToUpper();
            Damage.EvaluatorId = UcEvaluatorDDL.SelectedId;
            if (Damage.EvaluatorId.HasValue)
                Damage.EvaluatorName = dl.Evaluators.Where(e => e.EvaluatorId == Damage.EvaluatorId).First().EvaluatorName.ToUpper();
            Damage.InsurerId = ucInsDDL.SelectedId;
            if (Damage.InsurerId.HasValue)
                Damage.InsurerName = dl.Insurers.Where(i => i.InsurerId == Damage.InsurerId).First().InsurerName.ToUpper();
            Damage.Car.PaintId = UcPaintDDL.SelectedId;
            if (Damage.Car.PaintId.HasValue)
                Damage.Car.PaintName = dl.Paints.Where(i => i.PaintId == Damage.Car.PaintId).First().PaintName.ToUpper();
            Damage.Car.Owner.CountryId = ucRegional.CountryId.Value;
            if (Damage.Car.Owner.CountryId.HasValue)
                Damage.Car.Owner.CountryName = dl.Countries.Where(i => i.CountryId == Damage.Car.Owner.CountryId).First().CountryName.ToUpper();
            Damage.Car.Owner.DistrictId = ucRegional.DistrictId.HasValue ? ucRegional.DistrictId.Value : (Guid?)null;
            if (ucRegional.DistrictId.HasValue)
                Damage.Car.Owner.DistrictName = dl.Districts.Where(i => i.DistrictId == Damage.Car.Owner.DistrictId).First().DistrictName.ToUpper();
            Damage.Car.Owner.CityId = ucRegional.CityId.HasValue ? ucRegional.CityId.Value : (Guid?)null;
            if (ucRegional.CityId.HasValue)
                Damage.Car.Owner.CityName = dl.Cities.Where(i => i.CityId == Damage.Car.Owner.CityId).First().CityName.ToUpper();
            Damage.Car.MakeId = ucVehicles.MakeId.HasValue ? ucVehicles.MakeId.Value : (Guid?)null;
            if (ucVehicles.MakeId.HasValue)
                Damage.Car.MakeName = dl.Makes.Where(i => i.MakeId == Damage.Car.MakeId).First().MakeName.ToUpper();
            Damage.Car.ModelId = ucVehicles.ModelId.HasValue ? ucVehicles.ModelId.Value : (Guid?)null;
            if (ucVehicles.ModelId.HasValue)
                Damage.Car.ModelName = dl.Models.Where(i => i.ModelId == Damage.Car.ModelId).First().ModelName.ToUpper();
            Damage.Car.Owner.Emails = tbEmails.Text;
        }

        protected void bNext_Click(object sender, EventArgs e)
        {
            Page.Validate("vg");
            if (Page.IsValid)
            {
                GetData();
                Response.Redirect("calc.aspx", true);
            }

        }

        protected void cvDamageDate_ServerValidate(object source, ServerValidateEventArgs args)
        {
            DateTime d;
            args.IsValid = DateTime.TryParse(tbDamageDate.Text, out d);
        }

        protected void tAutoSave_Tick(object sender, EventArgs e)
        {
            GetData();
            DB.Draft draft = dl.Drafts.FirstOrDefault(d => d.UserId == this.UserId);
            if (draft == null)
            {
                draft = new DB.Draft();
                dl.Drafts.InsertOnSubmit(draft);
            }
            draft.UserId = this.UserId.Value;
            draft.DraftXML = this.Damage.GetXml();
            dl.SubmitChanges();

        }



    }
}